package com.examplemartin.jpademo.controller.stock.pur;


import com.examplemartin.jpademo.bean.AjaxResult;
import com.examplemartin.jpademo.pojo.po.UserPO;
import com.examplemartin.jpademo.pojo.po.purchase.PurDetailPO;
import com.examplemartin.jpademo.pojo.po.purchase.PurPO;
import com.examplemartin.jpademo.pojo.po.repository.purchase.PurInPO;
import com.examplemartin.jpademo.pojo.po.supplier.SupplierPO;
import com.examplemartin.jpademo.pojo.vo.purchase.PurDetailVO;
import com.examplemartin.jpademo.pojo.vo.purchase.PurVOForPurin;
import com.examplemartin.jpademo.service.GoodService;
import com.examplemartin.jpademo.service.RepoInfoService;
import com.examplemartin.jpademo.service.StockService;
import com.examplemartin.jpademo.service.SupplierService;
import com.examplemartin.jpademo.service.UserService;
import com.examplemartin.jpademo.service.pur.PurDetailService;
import com.examplemartin.jpademo.service.pur.PurchaseService;
import com.examplemartin.jpademo.service.purin.PurInDetailService;
import com.examplemartin.jpademo.service.purin.PurInService;
import com.examplemartin.jpademo.util.SessionUtil;
import com.examplemartin.jpademo.util.ValidateMember;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Log4j2
@Controller
@RequestMapping("/purin")
public class PurInController {

  @Resource
  private PurInService purInService;

  @Resource
  private PurchaseService purchaseService;

  @Resource
  private UserService userService;

  @Resource
  private GoodService goodService;

  @Resource
  private PurInDetailService purInDetailService;

  @Resource
  private RepoInfoService repoInfoService;

  @Resource
  private StockService stockService;

  @Resource
  private SupplierService supplierService;

  @Resource
  private PurDetailService purDetailService;


  /**
   * purinstock.do 跳转到采购入库单列表界面
   */
  @GetMapping("/purinstock.do")
  public String purinstockDo(
      @RequestParam(name = "purname", required = false) String purname,
      @RequestParam(name = "inname", required = false) String inname,
      @RequestParam(name = "statusid", required = false) String statusid,
      @RequestParam(name = "supplierid", required = false) String supplierid,
      Model model
  ) {
    model.addAttribute("title", "采购入库单");

    Integer stuatus = null;
    if (!ValidateMember.isEmpty(statusid)) {
      stuatus = Integer.valueOf(statusid);
    } else {
      stuatus = null;
    }

    Long supplier = null;
    if (!ValidateMember.isEmpty(supplierid)) {
      supplier = Long.valueOf(supplierid);
    } else {
      supplier = null;
    }

    if (ValidateMember.isEmpty(purname)) {
      purname = null;
    }

    if (ValidateMember.isEmpty(inname)) {
      inname = null;
    }

    List<PurInPO> all = purInService.findAll(purname, inname, supplier, stuatus);

    model.addAttribute("purinlist", all);

    model.addAttribute("purinstatus", PurInService.PURIN_STATUS_MAP);

    List<SupplierPO> supplierPOList = supplierService.findAll();

    model.addAttribute("supplierlist", supplierPOList);

    return "stock/purchase/purinstocklist";
  }

  /**
   * /newPurIn.do 跳转到 新建采购入库单 界面
   */
  @GetMapping("/newPurIn.do")
  public String newPurInDo(Model model,
      @RequestParam(name = "purid", required = false) Long purid) {
    model.addAttribute("title", "新建采购入库单");

    // 获取执行中的 采购订单
    List<PurPO> running = purchaseService.findByStatus(PurchaseService.PURPO_STATUS_RUNNING);

    ArrayList<PurVOForPurin> purVOForPurinList = new ArrayList<>();
    for (PurPO runningpurPO : running) {
      PurVOForPurin purVOForPurin = new PurVOForPurin();

      purVOForPurin.setUserPO(runningpurPO.getUserPO());
      purVOForPurin.setStatus(runningpurPO.getStatus());
      purVOForPurin.setId(runningpurPO.getId());
      purVOForPurin.setNeed(runningpurPO.getNeed());
      purVOForPurin.setCreateTime(runningpurPO.getCreateTime());
      purVOForPurin.setName(runningpurPO.getName());
      purVOForPurin.setComment(runningpurPO.getComment());
      purVOForPurin.setStatus(runningpurPO.getStatus());
      if (runningpurPO.getPurDetailPOList() != null
          && runningpurPO.getPurDetailPOList().size() > 0) {
        purVOForPurin.setPurDetailVOList(new ArrayList<PurDetailVO>());
        List<PurDetailPO> purDetailPOList = runningpurPO.getPurDetailPOList();
        for (PurDetailPO purDetailPO : purDetailPOList) {
          PurDetailVO vo = new PurDetailVO();
          vo.setGoodPO(purDetailPO.getGoodPO());
          vo.setGoodcount(purDetailPO.getGoodcount());
          vo.setId(purDetailPO.getId());

          List<Object[]> sums = purInDetailService
              .sumGroupbyGoodidAndpurid(purVOForPurin.getId(), vo.getGoodPO().getId());
          if (sums == null || sums.size() == 0) {
            vo.setInStockCount(0);
          } else if (sums.size() > 1) {
            vo.setInStockCount(-9999);
          } else {
            int i = Integer.parseInt(sums.get(0)[0].toString());
            vo.setInStockCount(i);
          }
          purVOForPurin.getPurDetailVOList().add(vo);
        }
      }
      purVOForPurinList.add(purVOForPurin);
    }
    model.addAttribute("purlist", purVOForPurinList);

    return "stock/purchase/newPurIn";
  }

  /**
   * 新建采购入库单 -- 包括明细
   */
  @PostMapping("/savepurin.ajax")
  @ResponseBody
  public AjaxResult savePurInAjax(@RequestBody PurInPO purInPO) {

    UserPO loninUser = SessionUtil.getLoninUser();
    UserPO userById = userService.findUserById(loninUser.getId());
    purInPO.setUserPO(userById);

    // purInPO 交付 server 处理

    AjaxResult result = purInService.newPurIn(purInPO);
    if (result.getCode() != 200) {
      return AjaxResult.fail(result.getCode(), result.getMsg());
    } else {
      PurInPO newpurInPO = (PurInPO) result.getData().get("purInPO");
      return AjaxResult.success(200, newpurInPO.getName() + ": 入库单保存成功", null);
    }

    // 更新库存
        /*List<PurInDetailPO> purInDetailPOList = save.getPurInDetailPOList();
        for (PurInDetailPO purInDetailPO : purInDetailPOList) {
            GoodPO goodPO = purInDetailPO.getGoodPO();
            Integer count = purInDetailPO.getGoodcount();
            RepoInfoPO repoInfoPO = new RepoInfoPO();

            // 获取用户关联的仓库
            StockPO stockbyId = stockService.findById(userById.getStockPO().getId());

            // 设定入库数量
            repoInfoPO.setGoodcount(count);


            // 查询 -- 根据商品和仓库
            List<RepoInfoPO> allByStockPOAndGoodPO = repoInfoService.findAllByStockPOAndGoodPO(stockbyId, goodPO);

            if (allByStockPOAndGoodPO == null || allByStockPOAndGoodPO.size() <= 0) // 仓储没有条目, 新建
            {
                // 设定商品
                repoInfoPO.setGoodPO(goodPO);
                // 设定仓库
                repoInfoPO.setStockPO(stockbyId);

                RepoInfoPO ret = repoInfoService.save(repoInfoPO);
                if (ret == null) {
                    return AjaxResult.success(200, "入库单保存成功", null);
                } else {
                    return AjaxResult.fail(500, "入库单保存失败");
                }
            }

            if (allByStockPOAndGoodPO.size() > 1) // 仓储有冲突
            {
                return AjaxResult.fail(500, "仓储条目有冲突");
            }

            if (allByStockPOAndGoodPO.size() == 1) {
                RepoInfoPO repoInfoPO1 = allByStockPOAndGoodPO.get(0);
                repoInfoPO1.setGoodcount(repoInfoPO1.getGoodcount() + count);
                RepoInfoPO ret = repoInfoService.save(repoInfoPO1);
                if (ret == null) {
                    return AjaxResult.fail(500, "入库单保存失败");
                }
            }
        }*/

  }

  /**
   * 编辑采购入库单
   */
  @GetMapping("/editpurin.do")
  public String editpurinDo(Long id, Model model) throws CloneNotSupportedException {
    model.addAttribute("title", "编辑采购入库单");

    PurInPO purInPO = purInService.editpurinDo(id);

    model.addAttribute("purIn", purInPO);

    return "stock/purchase/editPurIn";
  }

  /**
   * 保存修改的入库单 /editpurin.ajax
   */
  @PostMapping("/editpurin.ajax")
  @ResponseBody
  public AjaxResult editpurinAjax(@RequestBody PurInPO purInPO) {

    AjaxResult result = purInService.editpurinAjax(purInPO);

    return result;
  }


  /**
   * 采购入库单审核
   */
  @GetMapping("/auditpurin.do")
  public String auditpurinDo(Long id, Model model) throws CloneNotSupportedException {
    model.addAttribute("title", "采购入库单审核");

    List<PurInPO> allsort = purInService.findAllsort();

    model.addAttribute("purInlist", allsort);
    model.addAttribute("purinstatus", PurInService.PURIN_STATUS_MAP);

    return "stock/purchase/auditPurIn";
  }

  /**
   * 跳转到审核入库单界面
   * @param id
   * @param model
   * @return
   */
  @GetMapping("/auditeditpurin.do")
  public String auditeditpurinDo(Long id,Model model){
    PurInPO purinbyId = purInService.findById(id);
    model.addAttribute("purinstatus", PurInService.PURIN_STATUS_MAP);
    model.addAttribute("title","入库单审核");
    model.addAttribute("purIn",purinbyId);

    return "stock/purchase/auditeditPurIn";
  }

  /**
   * ajax 审核入库单
   * @return
   */
  @PostMapping("/auditPurIn.ajax")
  @ResponseBody
  public AjaxResult auditPurInAjax(@RequestBody PurInPO purInPO){
    /**
     * 0 编制
     * 1 入库
     * 3 废弃
     */
    Long id = purInPO.getId();
    Integer status = purInPO.getStatus();
    if(ValidateMember.isEmpty(id)||ValidateMember.isEmpty(status)){
      return AjaxResult.fail(500, "数据有误, 请重新检查");
    }

    AjaxResult result = purInService.auditPurInAjax(id, status);
    return result;
  }
}
